<script setup>
import { computed, onMounted, ref } from "vue";
import {
  Delete,
  Edit,
  View,
  ArrowUp,
  ArrowDown,
  Document,  // 添加文档图标用于重新提交审核
} from "@element-plus/icons-vue";
import { formatDate } from "@/utils/day";
import VideoPlayModal from "../../../Selected/components/VideoPlayModal.vue";
import { ElMessageBox } from "element-plus"; // 引入 ElMessageBox 用于确认
import { formatDuration } from '@/utils/time'; // 导入视频时长格式化工具函数

// 新增：视频编辑表单相关状态
const showEditDialog = ref(false);
const editForm = ref({
  title: '',
  description: '',
  categoryId: ''
});
const editLoading = ref(false);

const props = defineProps({
  video: {
    type: Object,
    required: true,
  },
  // 新增：接收分类列表
  categories: {
    type: Array,
    default: () => []
  }
});

const emit = defineEmits(["delete", "status-change", "resubmit", "update"]);

// 处理删除
const handleDelete = () => {
  emit("delete", props.video.video_id);
};

// 处理状态变更
const handleStatusChange = (status) => {
  emit("status-change", props.video.video_id, status);
};

// 处理重新提交审核
const handleResubmit = (videoId) => {
  emit("resubmit", videoId);
};

// 新增：打开编辑对话框
const openEditDialog = () => {
  // 初始化表单数据
  editForm.value = {
    title: props.video.title || '',
    description: props.video.description || '',
    categoryId: String(props.video.category?.id) || ''
  };
  showEditDialog.value = true;
};

// 新增：提交编辑表单
const submitEditForm = () => {
  if (!editForm.value.title.trim()) {
    ElMessage.warning('标题不能为空');
    return;
  }
  
  editLoading.value = true;

  // 触发更新事件，传递给父组件处理
  emit("update", props.video.video_id, editForm.value);
  
  // 这里假设父组件会处理实际的API调用，然后我们只需关闭对话框
  setTimeout(() => {
    editLoading.value = false;
    showEditDialog.value = false;
  }, 300);
};

// 视频预览相关状态
const showPlayModal = ref(false);
const currentVideo = ref(null);

// 打开视频预览
const openVideoPreview = () => {
  // 将视频数据转换为模态框所需的格式
  currentVideo.value = {
    id: props.video.video_id,
    title: props.video.title,
    description: props.video.description || "暂无描述",
    src: props.video.oss_url, 
    coverUrl: props.video.cover_url,
    likeCount: props.video.like_count || 0,
    commentCount: props.video.comment_count || 0,
    shareCount: props.video.share_count || 0,
    isLiked: false,

    // 作者信息
    author: {
      id: props.video.user?.id,
      name: props.video.user?.username || "未知用户",
      avatar: props.video.user?.avatar || "",
      isFollowed: false,
    },
  };
  console.log('currentVideo:', currentVideo.value);
  showPlayModal.value = true;
};

// 关闭视频预览
const closePlayModal = () => {
  showPlayModal.value = false;
};

// 进入全屏模式
const enterFullscreen = () => {
  // 这里可以添加全屏逻辑，或者交由模态框内部处理
};

// 跳转到视频详情页
const goToVideoDetails = () => {
  closePlayModal();
  // 使用路由导航到视频详情页
  // $router.push(`/video/${props.video.id}`);
};

// 视频状态相关计算属性
const statusText = computed(() => {
  const statusMap = {
    approved: "公开",
    hidden: "隐藏",
    pending: "审核",
    rejected: "驳回",
    manualReview: "人工审核",
  };
  return statusMap[props.video.status] || "未知状态";
});

const statusClass = computed(() => {
  return `status-${props.video.status}`;
});

// 格式化播放量
const formatViewCount = (count) => {
  if (count === undefined || count === null) return "0";
  if (count < 1000) return count.toString();
  if (count < 10000) return (count / 1000).toFixed(1) + "K";
  return (count / 10000).toFixed(1) + "W";
};

onMounted(() => {
})
</script>

<template>
  <div class="video-item">
    <div class="video-cover">
      <el-image :src="video.cover_url" fit="cover" />
    </div>

    <div class="video-info">
      <h3 class="video-title">{{ video.title }}</h3>

      <div class="video-meta">
        <div class="meta-item">
          <span class="label">状态：</span>
          <span :class="['status', statusClass]">{{ statusText }}</span>
        </div>
        <div class="meta-item">
          <span class="label">发布时间：</span>
          <span>{{ formatDate(video.created_at) }}</span>
        </div>
        <div class="meta-item">
          <span class="label">播放量：</span>
          <span>{{ formatViewCount(video.viewCount) }}</span>
        </div>
        <div class="meta-item">
          <span class="label">点赞数：</span>
          <span>{{ video.like_count || 0 }}</span>
        </div>
      </div>

      <!-- 如果是被驳回的视频显示驳回原因 -->
      <div class="video-description" v-if="video.status === 'rejected'">
        <span class="label">驳回原因：</span>
        {{ video.audit_reason || "未知原因" }}
      </div>

      <div class="video-description">
        <span class="label">描述：</span>
        {{ video.description || "暂无描述" }}
      </div>

      <div class="video-tags" v-if="video.category">
        <span class="label">分类：</span>
        {{ video.category.name }}
        <span class="label" style="margin-left: 10px;">时长：</span>
        {{ formatDuration(video.duration) || 0 }}
      </div>
    </div>

    <div class="video-actions">
      <!-- 查看按钮 -->
      <el-tooltip content="查看视频" placement="top">
        <el-button
          type="primary"
          :icon="View"
          circle
          link
          @click="openVideoPreview"
          style="margin-left: 12px"
        />
      </el-tooltip>

      <!-- 编辑按钮 -->
      <el-tooltip content="编辑视频" placement="top" v-if="video.status !== 'pending'">
        <el-button
          type="primary"
          :icon="Edit"
          circle
          link
          @click="openEditDialog" 
        />
      </el-tooltip>

      <!-- 状态操作按钮 -->
      <template v-if="video.status === 'approved'">
        <el-tooltip content="下线视频" placement="top">
          <el-button
            type="warning"
            :icon="ArrowDown"
            circle
            link
            @click="handleStatusChange('hidden')"
          />
        </el-tooltip>
      </template>
      <template
        v-else-if="video.status === 'hidden'"
      >
        <el-tooltip content="上线视频" placement="top">
          <el-button
            type="success"
            :icon="ArrowUp"
            circle
            link
            @click="handleStatusChange('approved')"
          />
        </el-tooltip>
      </template>

      <!-- 删除按钮 -->
      <el-tooltip content="删除视频" placement="top">
        <el-button
          type="danger"
          :icon="Delete"
          circle
          link
          @click="handleDelete"
        />
      </el-tooltip>

      <!-- 在视频操作区域添加 -->
      <template v-if="video.status === 'rejected'">
        <el-tooltip content="重新提交审核" placement="top">
          <el-button
            type="primary"
            icon="Refresh"
            circle
            link
            @click="handleResubmit(video.video_id)"
          />
        </el-tooltip>
      </template>
    </div>
  </div>

  <!-- 视频播放模态框 -->
  <VideoPlayModal
    :show="showPlayModal"
    :video="currentVideo"
    @close="closePlayModal"
    @fullscreen="enterFullscreen"
    @details="goToVideoDetails"
  />
  
  <!-- 编辑视频对话框 -->
  <el-dialog
    v-model="showEditDialog"
    title="编辑视频信息"
    width="500px"
    destroy-on-close
  >
    <el-form :model="editForm" label-width="80px">
      <el-form-item label="视频标题" required style="margin-bottom: 10px;">
        <el-input 
          v-model="editForm.title" 
          placeholder="请输入视频标题"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>
      
      <el-form-item label="视频分类" style="margin-bottom: 10px;">
        <el-select 
          v-model="editForm.categoryId" 
          placeholder="请选择分类"
          style="width: 100%"
        >
          <el-option
            v-for="category in categories"
            :key="category.value"
            :label="category.label"
            :value="category.value"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="视频描述" style="margin-bottom: 10px;">
        <el-input 
          v-model="editForm.description" 
          type="textarea" 
          :rows="4"
          placeholder="请输入视频描述"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="showEditDialog = false">取消</el-button>
        <el-button type="primary" @click="submitEditForm" :loading="editLoading">
          保存
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.video-item {
  display: flex;
  margin-bottom: 20px;
  padding: 16px;
  border-radius: 8px;
  background-color: #f9f9f9;
  transition: transform 0.2s ease, box-shadow 0.2s ease;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }
}

.video-cover {
  width: 180px;
  height: 100px;
  border-radius: 6px;
  overflow: hidden;
  margin-right: 16px;
  flex-shrink: 0;

  .el-image {
    width: 100%;
    height: 100%;
  }
}

.video-info {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 6px 0;
}

.video-title {
  font-size: 16px;
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color: #000;
}

.video-meta {
  display: flex;
  gap: 16px;
  font-size: 13px;
  color: #666;
}

.meta-item {
  .label {
    color: #999;
  }
}

.status {
  &.status-approved {
    color: #67c23a;
  }

  &.status-hidden {
    color: #909399;
  }

  &.status-pending {
    color: #e6a23c;
  }

  &.status-rejected {
    color: #f56c6c;
  }
}

.video-description {
  font-size: 13px;
  color: #666;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.video-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  font-size: 13px;
  color: #666;
}

.video-actions {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  padding-left: 16px;
  border-left: 1px solid #eee;
  margin-left: 16px;
}

// 编辑对话框样式
:deep(.el-dialog__body) {
  padding-top: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>